package async;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;

import javax.crypto.Cipher;

/**
 * @author chenzhiqiang
 * @date 2018-05-11 17:30:33
 */
public class test {

    public static void main(String[] args) throws Exception {
        byte[] msg = "test!中文".getBytes("UTF8"); // 待加解密的消息
        // 用证书的公钥加密
        CertificateFactory cff = CertificateFactory.getInstance("X.509");
        FileInputStream fis1 = new FileInputStream("E://keytool//certfile.cer"); // 证书文件
        java.security.cert.Certificate cf = cff.generateCertificate(fis1);
        PublicKey pk1 = cf.getPublicKey(); // 得到证书文件携带的公钥
        Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // 定义算法：RSA
        c1.init(Cipher.ENCRYPT_MODE, pk1);
        byte[] msg1 = c1.doFinal(msg); // 加密后的数据

        // 用证书的私钥解密 - 该私钥存在生成该证书的密钥库中
        FileInputStream fis2 = new FileInputStream("C://keytool//privateKeys.store");
        KeyStore ks = KeyStore.getInstance("JKS"); // 加载证书库
        char[] kspwd = "test123".toCharArray(); // 证书库密码
        char[] keypwd = "test456".toCharArray(); // 证书密码
        ks.load(fis2, kspwd); // 加载证书
        PrivateKey pk2 = (PrivateKey) ks.getKey("TestKey2", keypwd); // 获取证书私钥
        fis2.close();
        Cipher c2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        c2.init(Cipher.DECRYPT_MODE, pk2);
        byte[] msg2 = c2.doFinal(msg1); // 解密后的数据

        System.out.println(new String(msg2, "UTF8")); // 将解密数据转为字符串
    }
}
